import EmployeeForm from '@/components/EmployeeForm/EmployeeForm.vue'
import EmployeeImport from '@/components/EmployeeImport/EmployeeImport.vue'

import {
    addEmployeeApi,
    deleteEmployeeApi,
    updateEmployeeApi,
    pageListEmployeeApi,
    getEmployeeByIdApi,
    exportEmployeesApi
} from '@/api/Employee';
import {getAllCompaniesIdAndNameApi} from '@/api/Company';

export default {
    name: 'EmployeePage',
    components: {EmployeeForm, EmployeeImport},
    data() {
        return {
            // 员工列表数据
            employeeList: [],
            // 公司下拉选项
            companyOptions: [],
            // 加载状态
            loading: false,
            // 搜索关键词
            searchKeyword: '',
            // 搜索公司ID
            searchCompanyId: null,
            // 分页信息
            pagination: {
                current: 1,
                size: 10,
                total: 0
            },
            // 对话框相关
            dialogVisible: false,
            dialogTitle: '新增员工',
            // 表单数据
            formData: {},
            formLoading: false,
            //导入导出
            showImportDialog: false,
            exportLoading: false
        };
    },
    mounted() {
        this.fetchCompanyOptions();
        this.fetchEmployeeList();
    },
    methods: {
        // 导入成功后数据刷新
        handleImportSuccess() {
            this.pagination.current = 1
            this.fetchEmployeeList()
        },

        // 获取公司下拉选项
        async fetchCompanyOptions() {
            try {
                const response = await getAllCompaniesIdAndNameApi();
                console.log(response)
                this.companyOptions = response.data || [];
            } catch (error) {
                console.error('获取公司列表失败:', error);
                this.$message.error(error.message || '获取公司列表失败');
            }
        },

        // 获取员工列表
        async fetchEmployeeList() {
            this.loading = true;
            try {
                const response = await pageListEmployeeApi(
                    this.pagination.current,
                    this.pagination.size,
                    this.searchKeyword,
                    this.searchCompanyId
                );
                const data = response.data;
                // 将员工列表中的公司ID转换为公司名称
                this.employeeList = (data.list || []).map(employee => {
                    const company = this.companyOptions.find(c => c.id === employee.companyId);
                    return {
                        ...employee,
                        companyName: company ? company.name : '未知公司'
                    };
                });

                this.pagination.total = data.total || 0;
            } catch (error) {
                console.error('获取员工列表失败:', error);
                this.$message.error(error.message || '获取员工列表失败');
            } finally {
                this.loading = false;
            }
        },


        // 处理搜索
        handleSearch() {
            this.pagination.current = 1;
            this.fetchEmployeeList();
        },

        // 处理分页大小变化
        handleSizeChange(size) {
            this.pagination.size = size;
            this.fetchEmployeeList();
        },

        // 处理当前页变化
        handleCurrentChange(current) {
            this.pagination.current = current;
            this.fetchEmployeeList();
        },

        // 打开新增对话框
        handleAdd() {
            this.dialogTitle = '新增员工';
            this.formData = {
                id: null,
                name: '',
                age: null,
                employmentDate: '',
                employed: true,
                companyId: null
            };
            this.dialogVisible = true;
        },

        // 打开编辑对话框
        async handleEdit(row) {
            this.dialogTitle = '编辑员工';
            const loadingInstance = this.$loading();
            try {
                // 获取员工信息
                const response = await getEmployeeByIdApi(row.id);
                const employeeDetails = response.data;

                this.formData = {...employeeDetails}
                this.dialogVisible = true;
            } catch (error) {
                console.error('获取员工信息失败:', error);
                this.$message.error(error.message || '获取员工信息失败');
            } finally {
                // 关闭加载状态
                loadingInstance.close();
            }
        },

        // 处理表单提交
        async handleFormSubmit(formData) {
            try {
                if (formData.id) {
                    // 更新员工
                    await updateEmployeeApi(formData);
                    this.$message.success('员工信息更新成功');
                } else {
                    // 添加员工
                    const response = await addEmployeeApi(formData);
                    this.$message.success(`员工添加成功，ID: ${response.data}`);
                }
                this.dialogVisible = false;
                await this.fetchEmployeeList();
            } catch (error) {
                console.error('操作失败:', error);
                this.$message.error(error.message || '操作失败');
            }
        },


        // 删除员工
        handleDelete(id) {
            this.$confirm('确定要删除该员工吗?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(async () => {
                try {
                    await deleteEmployeeApi(id);
                    this.$message.success('删除成功');
                    await this.fetchEmployeeList();
                } catch (error) {
                    console.error('删除失败:', error);
                    this.$message.error(error.message || '删除失败');
                }
            }).catch(() => {
            });
        },

        // 重置表单数据
        resetFormData() {
            this.formData = {
                id: null,
                name: '',
                age: null,
                employmentDate: '',
                employed: true,
                companyId: null
            };
        },

        // 导出员工
        async exportEmployees() {
            this.exportLoading = true;
            try {
                // 创建虚拟链接触发下载
                const link = document.createElement('a');
                link.style.display = 'none';
                document.body.appendChild(link);

                // 调用导出API
                const response = await exportEmployeesApi(
                    this.searchKeyword,
                    this.searchCompanyId
                );
                // 二进制内容校验
                if (!(response.data instanceof Blob)) {
                    throw new Error("返回非文件数据");
                }
                // 从响应头中获取文件名
                const contentDisposition = response.headers['content-disposition'];
                let fileName = '员工列表.xlsx';

                if (contentDisposition) {
                    const match = contentDisposition.match(/filename\*?=(?:utf-8'')?(.+)/i);
                    if (match && match[1]) {
                        fileName = decodeURIComponent(match[1]);
                    }
                }

                // 创建Blob对象并下载
                const blob = new Blob([response.data], {
                    type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
                });

                const url = window.URL.createObjectURL(blob);
                link.href = url;
                link.setAttribute('download', fileName);
                link.click();

                // 释放URL对象
                window.URL.revokeObjectURL(url);

            } catch (error) {
                console.error('导出失败', error)
                this.$message.error('导出失败: ' + (error.message || '系统错误'))
            } finally {
                this.exportLoading = false
            }
        },

        // 格式化日期
        formatDate(dateString) {
            if (!dateString) return '';
            const date = new Date(dateString);
            return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}`;
        }
    }
}
